import { reqCheckCart, reqDeleteCart, reqShopCartList } from '@/api';
const state = {
    shopcartList: []
}
const mutations = {
    RECEIVE_SHOPCARTLIST(state, data) {
        state.shopcartList = data
    }
}
const actions = {
    // 获取购物车列表
    async getShopcartList({ commit }) {
        const data = await reqShopCartList()
        if (data.code === 200) {
            commit('RECEIVE_SHOPCARTLIST', data.data[0])
        }
    },
    // 删除商品
    async deleteCart({ commit }, id) {
        const result = await reqDeleteCart(id)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new error('faile'))
        }
    },
    // 切换选中状态
    async changeChecked({ commit }, { skuID, isChecked }) {
        const result = await reqCheckCart(skuID, isChecked)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new error("faile"))
        }
    },
    // 全选
    Allchecked({ dispatch, getters }, isChecked) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = dispatch('changeChecked', { skuID: item.skuId, isChecked: isChecked })
            promiseAll.push(promise)
        });
    },
    // 删除选中的商品
    deleteAllChecked({ dispatch, getters }) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if (item.isChecked === 1) {
                let promise = dispatch("deleteCart", item.skuId)
                promiseAll.push(promise)
            }
        })
    }

}
const getters = {
    cartInfoList(state) {
        return state.shopcartList.cartInfoList || [];
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}